/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package roles;

import avenue.MyWindowEvent;
import avenue.Utils;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;
import users.*;

/**
 *
 * @author Aggelos
 */
public class EditRoleForm extends javax.swing.JFrame {

    /**
     * Creates new form EditUserForm
     */
    public EditRoleForm() {
        em = DBManager.em;
        initComponents();
        checkControls();
        Utils.centerOnScreen(this);
    }

    public EditRoleForm(UserRole ur, boolean readOnly) {
        em = DBManager.em;

        userRole1 = ur;
        this.readOnly = readOnly;
        initComponents();
        checkControls();
        Utils.centerOnScreen(this);
        if (userRole1.getId() != null) {
            jTxtRoleName.setEditable(false);
        } else {
            jTxtRoleName.setEditable(true);
        }
    }

    private void checkControls() {
        if (jTxtRoleName.getText().trim().equals("")) {
            jBtnSave.setEnabled(false);
            jBtnNew.setEnabled(false);
        } else {
            jBtnSave.setEnabled(true);
            jBtnNew.setEnabled(true);
        }
        s = jTable1.getSelectedRow();

        jBtnDelete.setEnabled(s >= 0);
        jBtnEdit.setEnabled(s >= 0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRole2 = userRole1;
        query1 = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",userRole2);
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        roleBoxRenderer1 = new avenue.RoleBoxRenderer();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jTxtRoleName = new javax.swing.JTextField();
        jBtnSave = new javax.swing.JButton();
        jBtnCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jBtnEdit = new javax.swing.JButton();
        jBtnDelete = new javax.swing.JButton();
        jBtnNew = new javax.swing.JButton();

        roleBoxRenderer1.setText("roleBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Όνομα Ρόλου : ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${roleName}"), jTxtRoleName, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTxtRoleName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtRoleNameKeyReleased(evt);
            }
        });

        jBtnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jBtnSave.setText("Αποθήκευση");
        jBtnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnSaveActionPerformed(evt);
            }
        });

        jBtnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jBtnCancel.setText("Ακυρο");
        jBtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${moduleId.description}"));
        columnBinding.setColumnName("Module");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canCreate}"));
        columnBinding.setColumnName("Εισαγωγή");
        columnBinding.setColumnClass(java.io.Serializable.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canRetrieve}"));
        columnBinding.setColumnName("Αναζήτηση");
        columnBinding.setColumnClass(java.io.Serializable.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canUpdate}"));
        columnBinding.setColumnName("Επεξεργασία");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canDelete}"));
        columnBinding.setColumnName("Διαγραφή");
        columnBinding.setColumnClass(java.io.Serializable.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationLevelAccess}"));
        columnBinding.setColumnName("Ορατότητα Σταθμού");
        columnBinding.setColumnClass(java.io.Serializable.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(200);
        jTable1.getColumnModel().getColumn(1).setMinWidth(70);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(2).setMinWidth(70);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(3).setMinWidth(80);
        jTable1.getColumnModel().getColumn(3).setMaxWidth(80);
        jTable1.getColumnModel().getColumn(4).setMinWidth(70);
        jTable1.getColumnModel().getColumn(4).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(5).setMinWidth(130);
        jTable1.getColumnModel().getColumn(5).setMaxWidth(130);

        jBtnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        jBtnEdit.setText("Επεξεργασία");
        jBtnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnEditActionPerformed(evt);
            }
        });

        jBtnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        jBtnDelete.setText("Διαγραφή");
        jBtnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnDeleteActionPerformed(evt);
            }
        });

        jBtnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        jBtnNew.setText("Νέο");
        jBtnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnNewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTxtRoleName, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jBtnNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBtnCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnSave)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTxtRoleName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnSave)
                    .addComponent(jBtnCancel)
                    .addComponent(jBtnNew)
                    .addComponent(jBtnDelete)
                    .addComponent(jBtnEdit))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelActionPerformed
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }//GEN-LAST:event_jBtnCancelActionPerformed

    private void jBtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSaveActionPerformed
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }//GEN-LAST:event_jBtnSaveActionPerformed

    private void jBtnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnNewActionPerformed
        // TODO add your handling code here:


        rp = new RolePermission();

        rp.setRoleId(userRole1);

        rp.setCanCreate(1);
        rp.setCanRetrieve(1);
        rp.setCanDelete(1);
        rp.setCanUpdate(1);
        rp.setStationLevelAccess(1);



        List<Module> list = em.createQuery("SELECT m FROM Module m").getResultList();
        List<RolePermission> list2 = em.createQuery("SELECT rp FROM RolePermission rp where rp.roleId=:roleId").setParameter("roleId", userRole1).getResultList();



        EditRolePermission epf = new EditRolePermission(rp);

        for (RolePermission rp : list2) {
            list.remove(rp.getModuleId());
        }



        for (Module m : list) {
            epf.addChoice(m.getDescription());
        }

        if (list.size() == 0) {
            JOptionPane.showMessageDialog(this, Utils.msgNoMoreRolePermissions, Utils.msgDialogTitle, JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        rp.setModuleId(list.get(0));




        epf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //************
        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (MyWindowEvent.isExitAndSave(arg0)) {

                    em.persist(rp);
                    list1.add(rp);
                    int row = list1.size() - 1;


                    jTable1.setRowSelectionInterval(row, row);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                } else {
                    thisFrame.setEnabled(true);


                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
                checkControls();
            }

            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });

    }//GEN-LAST:event_jBtnNewActionPerformed

    private void jBtnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnDeleteActionPerformed
        // TODO add your handling code here:
        int s = jTable1.getSelectedRow();
        if (s >= 0) {
            RolePermission rp = list1.get(jTable1.convertRowIndexToModel(s));
            em.remove(rp);
            list1.remove(rp);
        }
        checkControls();
    }//GEN-LAST:event_jBtnDeleteActionPerformed
    private void jBtnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEditActionPerformed
        // TODO add your handling code here:
        s = jTable1.getSelectedRow();

        rp = list1.get(s);
        EditRolePermission erpf = new EditRolePermission(rp);
        erpf.addChoice(rp.getModuleId().getDescription());
        erpf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //************
        erpf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (MyWindowEvent.isExitAndSave(arg0)) {

                    em.persist(rp);

                    list1.set(s, rp);
                    jTable1.setRowSelectionInterval(s, s);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                } else {
                    thisFrame.setEnabled(true);
                    /*em.getTransaction().rollback();
                     em.getTransaction().begin();*/
                    /*java.util.Collection data = query1.getResultList();
                     for (Object entity : data) {
                     em.refresh(entity);
                     }
                     list1.clear();
                     list1.addAll(data);*/
                }
                checkControls();
            }

            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_jBtnEditActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        checkControls();
        if (jBtnEdit.isEnabled() && (evt.getClickCount() > 1)) {
            jBtnEditActionPerformed(null);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTxtRoleNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtRoleNameKeyReleased
        checkControls();
    }//GEN-LAST:event_jTxtRoleNameKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditRoleForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnCancel;
    private javax.swing.JButton jBtnDelete;
    private javax.swing.JButton jBtnEdit;
    private javax.swing.JButton jBtnNew;
    private javax.swing.JButton jBtnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTxtRoleName;
    private java.util.List<RolePermission> list1;
    private javax.persistence.Query query1;
    private avenue.RoleBoxRenderer roleBoxRenderer1;
    private model.UserRole userRole2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    UserRole userRole1;
    JFrame thisFrame;
    int s;
    RolePermission rp;
    boolean readOnly;
}
